package 链表;

import common.ListNode;

/**
 * @author tmh
 * @date 2024/11/23 19:41
 * @description
 */
public class T25K个一组翻转链表 {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode tail = head;
        //易错点2：判断是否有k个元素，判断里面是小于等于的逻辑
        for (int i = 1; i <= k; i++) {
            if (tail == null) {
                return head;
            }
            tail = tail.next;
        }
        ListNode newHead = reverse(head, tail);
        //易错点1：这里是tail，例如 1 2 3 ，k=2，tail就因该是指向3，进入下一次的k次翻转
        head.next = reverseKGroup(tail, k);
        return newHead;
    }

    public ListNode reverse(ListNode head, ListNode tail) {
        ListNode pre = null;
        ListNode next;
        //这个就是翻转链表的模板，记住就行
        while (head != tail) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

}
